package com.bwie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.TbOrderDetailMapper;
import com.bwie.mapper.TbOrderRecordMapper;
import com.bwie.mapper.TbProdInfoMapper;
import com.bwie.poi.ExcelUtil;
import com.bwie.pojo.*;
import com.bwie.service.IUserService;
import com.bwie.service.TbOrderService;
import com.bwie.mapper.TbOrderMapper;
import com.bwie.utils.ExceptionUtils;
import com.bwie.utils.R;
import com.bwie.utils.TokenUtil;
import com.bwie.vo.OrderDetailVo;
import com.bwie.vo.OrderVo;
import jdk.nashorn.internal.parser.Token;
import jdk.nashorn.internal.runtime.PropertyListeners;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @author Lenovo
* @description 针对表【tb_order(订单表)】的数据库操作Service实现
* @createDate 2025-07-23 15:11:17
*/
@Service
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder>
    implements TbOrderService{

    @Autowired
    TbOrderMapper tbOrderMapper;
    @Autowired
    TbOrderDetailMapper tbOrderDetailMapper;
    @Autowired
    HttpServletRequest request;
    @Autowired
    HttpServletResponse response;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    TbProdInfoMapper tbProdInfoMapper;
    @Autowired
    TbOrderRecordMapper tbOrderRecordMapper;
    @Autowired
    IUserService iUserService;

    @Override
    public R getOrderList(OrderVo orderVo) {
        Page<TbOrder> page = new Page<>(orderVo.getPageNum(), orderVo.getPageSize());

        LambdaQueryWrapper<TbOrder> wrapper = new LambdaQueryWrapper<>();

        if(StringUtils.isNotEmpty(orderVo.getKeyWord())){
            wrapper.like(TbOrder::getProdInfo,orderVo.getKeyWord());
        }
        if(orderVo.getTypeId() != null){
            wrapper.eq(TbOrder::getOrderType,orderVo.getTypeId());
        }
        if(orderVo.getStatusId() != null){
            wrapper.eq(TbOrder::getOrderStatus,orderVo.getStatusId());
        }

        wrapper.orderByDesc(TbOrder::getOrderId);

        Page<TbOrder> tbOrderPage = tbOrderMapper.selectPage(page, wrapper);

        for (TbOrder record : tbOrderPage.getRecords()) {
            List<String> imageList = tbOrderMapper.getOrderImageList(record.getOrderId());

            ArrayList<String> list = new ArrayList<>();
            if(imageList!=null && imageList.size()>0){
                for (String s : imageList) {
                    if(s!=null){
                        List<String> strings = JSON.parseArray(s, String.class);
                        list.addAll(strings);
                    }
                }
            }
            record.setImageList(list);
        }

        return R.OK(tbOrderPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R deleteBatchOrder(List<Integer> ids) {
        if(ids==null && ids.size()<=0){
            return R.ERROR(404,"请选择您要删除的订单");
        }

        tbOrderMapper.deleteBatchIds(ids);

        tbOrderDetailMapper.delete(
                new LambdaQueryWrapper<TbOrderDetail>().in(TbOrderDetail::getOrderId,ids)
        );
        return R.OK();
    }

    @Override
    public void exportOrder(Integer userId) {
        ExcelUtil<TbOrder> excelUtil = new ExcelUtil<>(TbOrder.class);
        List<TbOrder> tbOrderList = tbOrderMapper.selectList(
                new LambdaQueryWrapper<TbOrder>().eq(TbOrder::getUserId, userId)
        );

        excelUtil.exportExcel(response,tbOrderList,"订单列表数据");
    }

    @Override
    public R addOrder(List<TbProdInfo> infoList) {
        String token = request.getHeader("token");
        if(token == null){
            return R.ERROR(404,"请先登录");
        }

        Integer userId = TokenUtil.userId(token);
        String userName = TokenUtil.userName(token);

        BigDecimal totalAmount = new BigDecimal("0.0");
        StringBuilder prodNames = new StringBuilder();

        RLock lock = redissonClient.getLock("order-lock");


        try {
            lock.lock();
            for (TbProdInfo tbProdInfo : infoList) {
                TbProdInfo prodInfo = tbProdInfoMapper.selectById(tbProdInfo.getInfoId());
                if(tbProdInfo.getBuyNum()>prodInfo.getProdStock()){
                    throw new RuntimeException("商品库存不够");
                }

                tbProdInfo.setProdStock(prodInfo.getProdStock() - tbProdInfo.getBuyNum());
                tbProdInfoMapper.updateById(tbProdInfo);

                totalAmount = totalAmount.add(tbProdInfo.getProdPrice().multiply(new BigDecimal(tbProdInfo.getBuyNum())));

                if(prodNames.length()>0){
                    prodNames.append(",");
                    prodNames.append(tbProdInfo.getProdName());
                }else{
                    prodNames.append(tbProdInfo.getProdName());
                }
            }
        } finally {
            lock.unlock();
        }

        TbOrder tbOrder = new TbOrder();
        long id = IdUtil.getSnowflake(1, 1).nextId();
        tbOrder.setOrderNo(id+"");
        tbOrder.setOrderAmount(totalAmount);
        tbOrder.setOrderStatus(0);
        tbOrder.setOrderType(1);
        tbOrder.setProdInfo(prodNames.toString());
        tbOrder.setCreateBy(userName);
        tbOrder.setCreateTime(new Date());
        tbOrder.setUserId(userId);
        tbOrderMapper.insert(tbOrder);

        for (TbProdInfo tbProdInfo : infoList) {
            TbOrderDetail tbOrderDetail = new TbOrderDetail();

            tbOrderDetail.setOrderId(tbOrder.getOrderId());
            tbOrderDetail.setInfoId(tbProdInfo.getInfoId());
            tbOrderDetail.setProdId(tbProdInfo.getProdId());
            tbOrderDetail.setBuyNum(tbProdInfo.getBuyNum());
            tbOrderDetail.setBuyPrice(tbProdInfo.getProdPrice());
            tbOrderDetail.setCreateBy(userName);
            tbOrderDetail.setCreateTime(new Date());
            tbOrderDetailMapper.insert(tbOrderDetail);
        }

        TbOrderRecord tbOrderRecord = new TbOrderRecord();
        tbOrderRecord.setOrderId(tbOrder.getOrderId());
        tbOrderRecord.setOptRecord("用户创建订单");
        tbOrderRecord.setCreateBy(userName);
        tbOrderRecord.setCreateTime(new Date());
        tbOrderRecordMapper.insert(tbOrderRecord);

        return R.OK();
    }

    @Override
    public R getOrderInfoById(Integer orderId) {
        TbOrder tbOrder = tbOrderMapper.selectById(orderId);
        if(tbOrder == null){
            return R.ERROR(404,"订单不存在");
        }

        R r = iUserService.getUserInfoById(tbOrder.getUserId());
        if(r.getCode() != 200){
            return r;
        }
        String s = JSON.toJSONString(r.getData());
        TbUser tbUser = JSON.parseObject(s, TbUser.class);
        tbOrder.setUser(tbUser);

        List<OrderDetailVo> orderDetailVoList = tbOrderMapper.getOrderDetailList(orderId);
        tbOrder.setDetailList(orderDetailVoList);

        List<TbOrderRecord> recordList = tbOrderMapper.getOrderRecordList(orderId);
        tbOrder.setRecordList(recordList);

        return R.OK(tbOrder);
    }
}




